﻿using AnlianCommon.API.Commands.Roles;
using AnlianCommon.Common.Domains.UserPermissions;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using AnlianCommon.Enum;
using AutoMapper;
using MediatR;

namespace AnlianCommon.API.Commands.Roles
{
    public class RoleCreateHander : IRequestHandler<RoleCreateCommand, Result>
    {
        private readonly IBaseRepository<Role> _roleRepository ;
        private readonly IMapper _mapper;



        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="_roleRepository"> 权限仓储</param>
        public RoleCreateHander(IBaseRepository<Role> roleRepository, IMapper mapper)
        {
            _roleRepository = roleRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 处理权限创建命令
        /// </summary>
        /// <param name="request"> 权限创建命令</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(RoleCreateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                Role role =_mapper.Map<Role>(request);

                var list = await _roleRepository.Add(role);
                if (list > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "添加成功";
                }
                else
                {
                    result.Msg = "添加失败";
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
